<?php

namespace App\Jobs\Zhunya;

use App\Models\CacheModel\BirthBoon;
use app\zyhsapi\model\ZyhsConsultRtcUserBenefits;
use Cache;
use Log;

use Illuminate\Bus\Queueable;
use Illuminate\Queue\SerializesModels;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;

class NewUserRegisterPackageSendJob implements ShouldQueue
{
    use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;

    public $jobData;

    /**
     * Create a new job instance.
     *
     * @param array $jobData
     */
    public function __construct(array $jobData)
    {
        $this->jobData = $jobData;
    }

    /**
     * Execute the job.
     *
     * @return void
     */
    public function task()
    {
      $jobData = $this->jobData;
      print_r(date('Y-m-d H:i:s') . '新手礼包赠送开始:uid=' . $jobData['uid'] . PHP_EOL);
        $jobAttempts = $job->attempts();
        if ($jobAttempts > 2)
        {   // 失败两次则删除队列任务
            $job->delete();
            return;
        }
        $nowTime = time();
        // 发放 准了 - 免费连线资格
        (new ZyhsConsultRtcUserBenefits())->SendRtcBenefits(2, [
            'app_type' => 2,
            'uid' => $jobData['uid'],
            'rtc_id' => 0,
            'type' => 1,    // 权益获取方式 1=>注册  2=>历史用户脚本发送 3=>后台赠送 4=>2014-07-18服务异常补偿领取
            'min' => 3,
            'aid' => 0,
            'create_time' => $nowTime,
            'expire_time' => $nowTime + 86400 * 7,  // 7 天有效期
            'use_time' => 0,
        ]);
        Cache::rm('reg_user_send_benefits_' . date('Ymd') . ':' . $jobData['uid']);

        $model = new BirthBoon();

        $res = $model->registerPackageBoonSend((int)$jobData['uid']);

        if (!$res)
        {
            Log::write("新手【{$jobData['uid']}】礼包赠送失败：" . $model->errorMsg, 'error');
            $job->release(60); // 延迟重启任务
            return;
        }

        Cache::set('has_new_user:id:' . $jobData['uid'], 1, 86400 * 7);
        print_r(date('Y-m-d H:i:s') . '新手礼包赠送结束:uid=' . $jobData['uid'] . PHP_EOL);
        $job->delete();
    }


}